package com.taurus.myboard.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.taurus.myboard.common.vo.Dict;
import com.taurus.myboard.pojo.FileInfoVo;
import com.taurus.myboard.pojo.UploadHistoryVo;
import com.taurus.myboard.service.IFateDataService;
import com.taurus.myboard.utils.HttpClientPool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Service
@Slf4j
public class FateDataServiceImpl implements IFateDataService {

    @Resource
    private RestTemplate restTemplate;
    @Resource
    private HttpClientPool httpClientPool;

    @Value("${fateflow.url}")
    private String url;

    @Override
    public Map<String, String> upLoadData(MultipartFile file, String table_name, Integer head, Integer partition,
                                          String namespace, Integer count, Integer drop) throws IOException {
//        String apiUrl = "http://123.207.217.102:9380/v1/data/upload";
        String apiUrl = url + "/v1/data/upload";
        MultiValueMap<String,Object> parts = new LinkedMultiValueMap<>();

//        String filePath = "/Users/kanten/fsdownload/breast_hetero_mini_guest.csv";
//        FileSystemResource fileSystemResource = new FileSystemResource(filePath);
        FileUtils.writeByteArrayToFile(new File(file.getOriginalFilename()), file.getBytes());
        FileSystemResource fileSystemResource = new FileSystemResource(new File(file.getOriginalFilename()));
        log.info("filename: {}, filesize: {}", file.getOriginalFilename(), file.getSize());

        MultiValueMap<String,Object> params = new LinkedMultiValueMap<>();
        HttpHeaders headers = new HttpHeaders();
        params.add("file",fileSystemResource);
        // TBD 以下信息从redis获取
        params.add("head", head);
        params.add("partition", partition);
        params.add("table_name",table_name);
        params.add("namespace", namespace);
        params.add("count", count);
        params.add("drop", drop);

        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<MultiValueMap<String,Object>> requestEntity  = new HttpEntity<>(params, headers);
        log.info("request to fate: {}", requestEntity.toString());
        String rst = restTemplate.postForObject(apiUrl,requestEntity ,String.class);
        JSONObject data = JSON.parseObject(rst).getJSONObject(Dict.DATA);
        log.info("response from fate: {}", data);
        Map<String, String> result = new HashMap<>();
        result.put("upload", rst);
        return result;
    }

    @Override
    public Map<String, Object> queryUploadHistory(String jobId, Integer limit, Long headIndex, Long tailIndex) {
        Map<String, Object> jobParams = new HashMap<>();
        jobParams.put(Dict.JOBID, jobId);
        jobParams.put(Dict.LIMIT, limit);
        Map<String, Object> result = new HashMap<>();
        String rst = httpClientPool.post(url + Dict.URL_UPLOAD_HISTORY, JSON.toJSONString(jobParams));
        JSONObject jo = JSON.parseObject(rst);
        JSONArray jd = jo.getJSONArray(Dict.DATA);
        result.put("total", jd.size());
        List<Map> infos = JSON.parseArray(jd.toJSONString(), Map.class);
        List<UploadHistoryVo> uploadHistoryVos = new ArrayList<>();
        Long dataCount = 0L;
        for (Map<String, Map> info : infos){
            Iterator<String> iterator = info.keySet().iterator();
            String historyJobId = iterator.next();
            if (++dataCount < headIndex) continue;
            if (dataCount > tailIndex) break;
            UploadHistoryVo uploadHistoryVo = new UploadHistoryVo();
            uploadHistoryVo.setJobId(historyJobId);
            Map<String, Object> uploadInfo = (Map<String, Object>) info.get(historyJobId).get("upload_info");
            uploadHistoryVo.setNamespace((String) uploadInfo.get("namespace"));
            uploadHistoryVo.setPartition((Integer) uploadInfo.get("partition"));
            uploadHistoryVo.setTable_name((String) uploadInfo.get("table_name"));
            uploadHistoryVo.setUpload_count((Integer) uploadInfo.get("upload_count"));
            uploadHistoryVos.add(uploadHistoryVo);
        }
        result.put("rows", uploadHistoryVos);
        return result;
    }

    @Override
    public Map<String, String> saveFileInfo(FileInfoVo fileInfoVo) {
        return null;
    }
}
